<?php

namespace app\http\middleware;

use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

class Auth
{
    /*
     * 用于验证请求方的 token
     */
    public function handle($request, Closure $next)
    {
        $bearer = $request->header('Authorization');    // 取header中的token
        if ($bearer != null) {
            list(, $token) = explode(" ", $bearer);
        } else {
            return json(['msg' => '用户未登录'], 401);
        }

        try {
            $de_token = JWT::decode($token, getJwtKey(), ['HS256']);
        } catch (SignatureInvalidException $exception) {
            // 捕获JWT解析错误
            return json(['msg' => '无效令牌'], 401);
        }

        if (time() > $de_token->exp) {
            return json(['msg' => '过期令牌'], 401);
        }

        $request->auth = $de_token->data->uid;

        return $next($request);
    }
}
